//
//  BrowseTableViewController.m
//  beautifulHome
//
//  Created by lanou on 15/12/17.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "BrowseTableViewController.h"
#import "LORequestManger.h"
#import "BrowseModel.h"
#import "BrowseFirstTableViewCell.h"
#import "BrowseSecondTableViewCell.h"
#import "BrowseThreeTableViewCell.h"
#import "BrowseScrollView.h"
#import "MJRefresh.h"
#import "DetailTableViewController.h"
#import "TaplmageView.h"
#import "DetailTowTableViewController.h"
#import "DetailViewController.h"
#import "ProfessorModel.h"
#import "MyLoginViewController.h"
#import "BhDataBase.h"
#import "DicData.h"
static NSInteger i = 0;
@interface BrowseTableViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) BrowseScrollView *mainHeader;

@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) NSMutableArray *picArray;
@property (nonatomic, strong) BrowseModel *browseModel;
@property (nonatomic, assign) NSInteger indexPath;

@end

@implementation BrowseTableViewController

// 懒加载
- (NSMutableArray *)array {
    
    if (!_array) {
        _array = [[NSMutableArray alloc]init];
    }
    return _array;
}
- (NSMutableArray *)picArray {
    if (!_picArray) {
        _picArray = [[NSMutableArray alloc]init];
    }
    return _picArray;
}



//- (NSMutableArray *)array {
//    
//    if (!_array) {
//        _array = [[NSMutableArray alloc]init];
//    }
//    return _array;
//}s

// 数据解析

- (void)setData {
     
    if ([DicData shops].count > 0) {
        for (NSDictionary *dic in [DicData shops]) {
            NSDictionary *dict = dic[@"data"];
            NSDictionary *picDic = dict[@"featured_banners2"];
            NSArray *bannersArray = picDic[@"banners"];
            for (NSDictionary *dic1 in bannersArray) {
                _browseModel = [[BrowseModel alloc] init];
                [_browseModel setValuesForKeysWithDictionary:dic1];
                
                [self.picArray addObject:_browseModel.pic];
            }
            
            // 轮播图
            
            _mainHeader = [[BrowseScrollView alloc]initWithFrame:(CGRectMake(10, 0, kWidth, 220)) targer:self action:@selector(tapImageTouch) imageArray:_picArray timer:3.5 selector:@selector(autoImage)];
            self.tableView.tableHeaderView = _mainHeader;
            
            NSDictionary *dicti = dict[@"featured_items"];
            NSArray *itemsArray = dicti[@"items"];
            for (NSDictionary *dictio in itemsArray) {
                _browseModel = [[BrowseModel alloc] init];
                [_browseModel setValuesForKeysWithDictionary:dictio];
                
                [self.array addObject:_browseModel];
            }

        }
    } else {
         [self setData1];
    }
}

- (void)setData1
{
     NSString *stringaaa =[NSString stringWithFormat:@"http://api.meilijia.com/app/featured_page3?page=%ld",(long)i];
     [LORequestManger GET:stringaaa success:^(id response) {
          //        _array = [[NSMutableArray alloc] init];
          //        self.picArray = [NSMutableArray array];
          // 删除数组里面元素
          [self.picArray removeAllObjects];
          NSDictionary *dic = (NSDictionary *)response;
          [DicData addshop:dic];
          NSDictionary *dict = dic[@"data"];
          NSDictionary *picDic = dict[@"featured_banners2"];
          NSArray *bannersArray = picDic[@"banners"];
          for (NSDictionary *dic1 in bannersArray) {
               _browseModel = [[BrowseModel alloc] init];
               [_browseModel setValuesForKeysWithDictionary:dic1];
               
               [self.picArray addObject:_browseModel.pic];
          }
          
          // 轮播图
         
          _mainHeader = [[BrowseScrollView alloc]initWithFrame:(CGRectMake(10, 0, kWidth, 220)) targer:self action:@selector(tapImageTouch) imageArray:_picArray timer:3.5 selector:@selector(autoImage)];
          self.tableView.tableHeaderView = _mainHeader;
          
          NSDictionary *dicti = dict[@"featured_items"];
          NSArray *itemsArray = dicti[@"items"];
          for (NSDictionary *dictio in itemsArray) {
               _browseModel = [[BrowseModel alloc] init];
               [_browseModel setValuesForKeysWithDictionary:dictio];
               
               [self.array addObject:_browseModel];
          }
          [self.tableView reloadData];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          
     }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setData];
    self.navigationItem.title = @"美丽家";
    // 设置字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]}];
    
    
    
    
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
    // 注册单元格
    [self.tableView registerClass:[BrowseFirstTableViewCell class] forCellReuseIdentifier:@"firstCell"];
    
    [self.tableView registerClass:[BrowseSecondTableViewCell class] forCellReuseIdentifier:@"secondCell"];
    
    [self.tableView registerClass:[BrowseThreeTableViewCell class] forCellReuseIdentifier:@"threeCell"];
    
    
    // 下拉刷新数据
    __weak BrowseTableViewController *browseVC = self;
   
     [self.tableView addHeaderWithCallback:^{
          
//          NSString *filestring =
//          [browseVC setData1];
          [browseVC.tableView headerEndRefreshing];
     }];
    [self.tableView addFooterWithCallback:^{
        i += 1;
        [browseVC setData1];
        [browseVC.tableView footerEndRefreshing];
    }];
    // 数据库名称
    [[BhDataBase shareSqliteBh] createSqliteTableWithName:@"bhTable"];
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"%ld",self.array.count);
    return self.array.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //判断单元格样式
    _browseModel = _array[indexPath.row];
    
    
    if ([_browseModel.type isEqualToString:@"2"] || [_browseModel.type isEqualToString:@"6"]) {
        BrowseFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firstCell" forIndexPath:indexPath];
        cell.browseModel = self.array[indexPath.row];
        if ([_browseModel.type isEqualToString:@"6"]) {
            cell.numberLabel.backgroundColor = [UIColor clearColor];
            cell.numberLabel.text = _browseModel.descr;
        }
        return cell;
    } else if ([_browseModel.type isEqualToString:@"1"]){
        BrowseSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"secondCell" forIndexPath:indexPath];
        cell.browseModel = self.array[indexPath.row];
    return cell;
    } else {
        BrowseThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"threeCell" forIndexPath:indexPath];
        cell.browseModel = self.array[indexPath.row];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoPersonalDetail:)];
        [cell.personalPictureView addGestureRecognizer:tap2];
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoDetail:)];
        cell.pictureView.tag = indexPath.row;
        cell.personalPictureView.tag = indexPath.row;
        [cell.pictureView addGestureRecognizer:tap1];
        //_indexPath = indexPath.row;
        UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shoucang:)];
        [cell.likeImageView addGestureRecognizer:tap3];
        cell.likeImageView.tag = indexPath.row;
        
        return cell;
        
    }
    
}

// 收藏按钮
- (void)shoucang:(UITapGestureRecognizer *)sender {
    NSLog(@"123");
    _browseModel = _array[sender.view.tag];
    for (BrowseModel *titleString in [[BhDataBase shareSqliteBh]selegetAllModel]) {
        if (titleString.ID == _browseModel.ID) {
            [[BhDataBase shareSqliteBh]deleteWithSingId:_browseModel.ID];
        }
    }
    [[BhDataBase shareSqliteBh]insertModel:_browseModel];
    
}
// 图片的点击事件
- (void)gotoDetail:(UITapGestureRecognizer *)sender {
    
    _browseModel = _array[sender.view.tag];
    NSLog(@"%ld",_indexPath);
    DetailTowTableViewController *detailTwoVC = [[DetailTowTableViewController alloc]init];
 
        detailTwoVC.browseModel = self.browseModel;
    
    [self.navigationController pushViewController:detailTwoVC animated:YES];
    
}

- (void)gotoPersonalDetail:(UITapGestureRecognizer *)sender{
    NSLog(@"小图片");
    DetailViewController *detailVC  = [[DetailViewController alloc] init];
    
     _browseModel = _array[sender.view.tag];
      ProfessorModel *model = [[ProfessorModel alloc]init];
    model.user_face = _browseModel.author_face;
    model.contacted_count = _browseModel.item_count;
    model.verified_work_count = _browseModel.view_count;
    model.location = _browseModel.title_sub_1;
    model.user_nick = _browseModel.author_nick;
    model.user_id = _browseModel.author_id;
    model.pro_price_min = _browseModel.buylist_total;
    model.pro_price_max = _browseModel.work_design_price;
    detailVC.professorModel = model;
    

    
    
    [self presentViewController:detailVC animated:YES completion:nil];
}

// 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    _browseModel = _array[indexPath.row];
    if ([_browseModel.type isEqualToString:@"work"]) {
        return kHeight / 2 + 110;
    } else {
    return kHeight / 2 + 10;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self scrollViewDidCircularly];
}

// tapImageView点击事件
- (void)tapImageTouch {
    NSInteger index = self.mainHeader.contentOffset.x / kWidth;
    NSLog(@"%ld",index);
    if (index == 0) {
        
        UIWebView *web = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        
        web.scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
        
        
        [web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.meilijia.com/activity/start1019?fromid=84&frm=start1019_iphone_ad"]]];
        
        [self.view addSubview:web];
        
    }
    if (index == 1) {
        
        UIWebView *web = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        
        web.scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
        
        
        [web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.meilijia.com/activity/freedesign0804?fromid=65&frm=freedesign0804_iphone_ad"]]];
        
        [self.view addSubview:web];
        
    }
    if (index == 2) {
        MyLoginViewController *MYvc = [[MyLoginViewController alloc]init];
        [self presentViewController:MYvc animated:YES completion:nil];
    }
    if (index == 3) {
         self.navigationController.tabBarController.selectedIndex = 1;
    }
    
    
    
}

// 定时器的执行方法
- (void)autoImage {
    [self scrollViewDidCircularly];
    CGPoint newPoint = self.mainHeader.contentOffset;
    newPoint.x += kWidth;
    [self.mainHeader setContentOffset:newPoint animated:YES];

}


- (void)scrollViewDidCircularly
{
    if (self.mainHeader.contentOffset.x == self.mainHeader.contentSize.width - kWidth) {
        [self.mainHeader setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    
}

// cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    _browseModel = _array[indexPath.row];
   
    if ([_browseModel.type isEqualToString:@"1"]) {
        DetailTableViewController *detailTVC = [[DetailTableViewController alloc]init];
        detailTVC.idString = _browseModel.ID;
        detailTVC.panDuan = @"设计";
        // title
        detailTVC.itemTitle = _browseModel.title;
        [self.navigationController pushViewController:detailTVC animated:YES];
        NSLog(@"1111");
        
    } else if ([_browseModel.type isEqualToString:@"2"]){
        DetailTableViewController *detailTVC = [[DetailTableViewController alloc]init];
        detailTVC.idString = _browseModel.ID;
        // title
        detailTVC.itemTitle = _browseModel.title;
        detailTVC.panDuan = @"灵感";
        [self.navigationController pushViewController:detailTVC animated:YES];
        NSLog(@"2222");
    }
    else {
        if ([_browseModel.type isEqualToString:@"6"]) {
             self.navigationController.tabBarController.selectedIndex = 1;
        }
        
    }
    
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
